package com.mayi.zds.service.imp;

import com.mayi.zds.entity.OrderStatusEntity;
import com.mayi.zds.service.OrderService;
import com.mayi.zds.service.ScanOrderStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @ClassName ScanOrderStatusService
 * @Author zhong
 * @Date 2019/12/26 10:35:13
 * @Version 1.0
 */
@Service
public class ScanOrderStatusServiceImp implements ScanOrderStatusService {

    private static Queue<OrderStatusEntity> orderQueue;
    static {
        orderQueue = new ArrayDeque<>();
    }

    @Autowired
    private OrderService orderService;

    @Override
    public void addOrder(OrderStatusEntity orderStatusEntity){
        orderQueue.add(orderStatusEntity);
    }

    public void addOrder(long triggerTime,String orderId){
        OrderStatusEntity orderStatusEntity = new OrderStatusEntity();
        orderStatusEntity.setTriggerTime(triggerTime);
        orderStatusEntity.setOrderId(orderId);
        orderStatusEntity.setToCancleOrder(true);

        this.addOrder(orderStatusEntity);
    }

    @Override
    @Scheduled(fixedRate = 1000,initialDelay = 600000)
    public void checkAndHandle(){
        System.out.println(System.currentTimeMillis());
        OrderStatusEntity head = orderQueue.peek();
        if(head!=null && head.getTriggerTime() <= System.currentTimeMillis()){
            OrderStatusEntity pollHead = orderQueue.poll();
            if(pollHead.isToCancleOrder()){
                orderService.cancle(pollHead.getOrderId());
                System.out.println("取消了订单：" + pollHead.getOrderId());
            }
        }
    }

    /**
     * 取消任务，将任务的toCancleOrder设为fasle
     *
     * @param orderId 订单ID
     * @return void
     * @Author zhong
     * @Date 2019/12/26 11:57:54
     **/
    @Override
    public void cancleTask(String orderId) {
        for (OrderStatusEntity orderStatusEntity : orderQueue) {
            if(orderStatusEntity.getOrderId().equals(orderId)){
                orderStatusEntity.setToCancleOrder(false);
                break;
            }
        }
    }
}


